package com.example.boos.createStore;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.MapView;
import com.bumptech.glide.Glide;
import com.example.boos.HttpUtil.MyPost;
import com.example.boos.R;
import com.example.boos.context.BossInfo;
import com.example.boos.map.ZdpMapView;
import com.example.boos.pojo.Store;
import com.example.boos.pojo.StoreAddress;
import com.example.boos.stores.stores_activity;
import com.example.boos.util.MyThreadPool;
import com.example.boos.util.ShowPopuWIndow;

import java.math.BigInteger;

public class createStoreActivity extends AppCompatActivity {

    // 普通控件
    private Button selectAddr;
    private RelativeLayout showAddr;
    private TextView addrAddress;
    private Button addrUpdateAddr;
    private EditText storeBottom;
    private EditText storeName;
    private EditText storeType;
    private Button createStore;
    private ImageView addStoreImage;
    private EditText storeNo;
    private EditText storeInfo;
    private MapView mMapView;
    private TextView imageSrc ;

    private StoreAddress storeAddress = new StoreAddress();
    private Store store = new Store();

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
                switch (msg.what){
                    case 1:
                        Toast.makeText(createStoreActivity.this,"店铺创建成功！",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName(createStoreActivity.this, stores_activity.class));
                        createStoreActivity.this.startActivity(intent);
                        break;
                    case 2:
                        Toast.makeText(createStoreActivity.this,"创建失败，请重试！",Toast.LENGTH_SHORT).show();
                        break;
                }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplication());
        setContentView(R.layout.activity_create_store);
        initView();
        initListener();

    }

    private void initView(){
        selectAddr =  findViewById(R.id.selectAddr);
        showAddr =  findViewById(R.id.showAddr);
        addrAddress  =  findViewById(R.id.addrAddress);
        addrUpdateAddr =  findViewById(R.id.addrUpdateAddr);
          storeBottom = findViewById(R.id.storeBottom);
          storeName  = findViewById(R.id.storeName);
          storeType  = findViewById(R.id.storeType);
          createStore  = findViewById(R.id.createStore);
          addStoreImage  = findViewById(R.id.addStoreImage);
          storeNo  = findViewById(R.id.storeNo);
          storeInfo  = findViewById(R.id.storeInfo);
        mMapView =  findViewById(R.id.addrBaiduMap);
        imageSrc = findViewById(R.id.imageUrl);
    }

    private void initListener(){
        // 创建店铺
        createStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 测试一下数据是否完整
                if(imageSrc.getText().toString() == null ||"".equals(imageSrc.getText().toString()) ){
                    Toast.makeText(createStoreActivity.this,"请选择店铺图片！",Toast.LENGTH_SHORT).show();
                    return ;
                }
                if(storeAddress.getAddress() == null ||"".equals(storeAddress.getAddress()) ||
                        storeBottom.getText().toString() == null ||"".equals(storeBottom.getText().toString()) ){
                    Toast.makeText(createStoreActivity.this,"请选择店铺地址！",Toast.LENGTH_SHORT).show();
                    return ;
                }
                // 设置以下数据
                // 先获取到 图片URL
                //  设置到 店铺信息中，创建店铺，获取到店铺Id
                // 店铺Id设置到店铺地址中，创建店铺地址
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        String url = "getImageUrl";
                        String imageUrl = (String) MyPost.uploadImage(url,imageSrc.getText().toString());
                        // 设置店铺的信息
                        store.setStoreStatus(1);
                        store.setStoreImage(imageUrl);
                        store.setBossId(BossInfo.bossId);
                        store.setStoreAddress(storeAddress.getAddress());
                        store.setStoreName(storeName.getText().toString());
                        store.setStoreType(storeType.getText().toString());
                        store.setStoreNo(BigInteger.valueOf(Long.parseLong(storeNo.getText().toString())));
                        store.setStoreInfo(storeInfo.getText().toString());
                        store = (Store) MyPost.doPost("addStore",store);
                        if(store.getId() == null){
                            // 创建失败
                            msg.what = 2;
                        }else{
                            // 创建成功 生成店铺地址
                            storeAddress.setBottome(storeBottom.getText().toString());
                            storeAddress.setStoreId(store.getId());
                            Boolean isSuccess = false;
                            int count = 0;
                            while(!isSuccess && count <=5){
                                isSuccess = (Boolean) MyPost.doPost("addStoreAddr",storeAddress);
                                count ++;
                            }
                            if(isSuccess){
                                // 成功
                                msg.what = 1;
                            }else{
                                // 失败 ，失败需要将刚才插入的店铺记录删除
                                MyPost.doPost("realDelStore",store.getId());
                                msg.what = 2;
                            }
                        }
                        handler.sendMessage(msg);
                    }
                });


            }
        });

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到 MapView 并希望带回一个返回值
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(createStoreActivity.this, ZdpMapView.class));
                intent.putExtra("fromActivity","createStoreActivity");
                createStoreActivity.this.startActivityForResult(intent,1);
            }
        };

        // 选择收货地址
        selectAddr.setOnClickListener(listener);
        // 修改收货地址
        addrUpdateAddr.setOnClickListener(listener);

        // 上传店铺图片
        addStoreImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowPopuWIndow.showPopueWindow(createStoreActivity.this,2);
            }
        });


    }

    private void showAddr(){
        showAddr.setVisibility(View.VISIBLE);
        selectAddr.setVisibility(View.GONE);
    }

    private void showUpdateAddr(){
        showAddr.setVisibility(View.GONE);
        selectAddr.setVisibility(View.VISIBLE);
    }

    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode == 1){
            if(resultCode == 1){
                // 将返回的结果 设置到 收货地址上
                Bundle bundle = data.getExtras();
                 storeAddress = (StoreAddress) bundle.get("StoreAddress");
                // 设置一下信息
                showAddr();
                addrAddress.setText(storeAddress.getAddress());
            }
        }
        if (resultCode == RESULT_OK ){
            if(requestCode == 2 && null != data){
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                //获取到图片的本地地址
                final String picturePath = cursor.getString(columnIndex);
                // 显示图片
                imageSrc = findViewById(R.id.imageUrl);
                imageSrc.setText(picturePath);
                Glide.with(this).load(picturePath).into(addStoreImage);
                cursor.close();
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}